import { existsSync, readFileSync, writeFileSync } from "fs";
import { Handler } from "./Handler";

export default class Config<T extends NonNullable<any>> extends Handler {
    /** @description 配置数据 */
    protected _data: T | null = null;

    public get data(): T | null {
        return this._data;
    }

    public set data(v: T) {
        this._data = v;
    }

    /** @description 配置文件路径 */
    get path(): string {
        return "";
    }

    /** @description 默认配置 */
    readonly defaultData: T | null = null;

    constructor() {
        super();
    }

    /**
     * @description 读取配置数据
     * @param isReload 是否强制重新读取配置数据
     * @returns 
     */
    read(isReload: boolean = false) {
        if (this.path) {
            if (!isReload && this._data) {
                return;
            }
            if (existsSync(this.path)) {
                let data = readFileSync(this.path, "utf-8");
                let source = JSON.parse(data);
                this._data = source as T;
            } else {
                if (this.defaultData) {
                    this._data = this.defaultData;
                    this.save();
                }
            }
        }
    }

    /** 
     * @description 保存配置数据
     */
    save() {
        if (this.path && this.data) {
            let data = JSON.stringify(this.data, null, 4);
            writeFileSync(this.path, data, "utf-8");
            this.logger.log(`${this.module} 保存 ${this.path} 配置数据 : ${data}`);
        } else {
            this.logger.log(`${this.module} 配置的路径或数据为空，无法保存配置`);
        }
    }
}